package com.mxchip.livestar.ui.groupcall


import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.mxchip.livestar.CallActivityA
import com.mxchip.livestar.R
import com.mxchip.livestar.base.CallLogViewModel
import com.mxchip.livestar.base.ContactViewModel
import com.mxchip.livestar.base.AppConstant
import com.mxchip.livestar.base.hideKeyboard
import com.mxchip.livestar.base.SystemData
import com.mxchip.livestar.base.toast
import com.mxchip.livestar.repository.RoomClientRepository
import com.mxchip.livestar.ui.P2PMultiCall
import com.mxchip.livestar.ui.P2PSingleCall
import kotlinx.android.synthetic.main.fragment_group_call.*
import java.util.*


class GroupCallFragment : Fragment(), TextWatcher, TextView.OnEditorActionListener {

    private val mAdapter: GroupCallAdapter by lazy {
        GroupCallAdapter()
    }

    private val contactViewModel by viewModels<ContactViewModel>()
    private val callLogViewModel by viewModels<CallLogViewModel>()

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_group_call, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        contact_search_key.addTextChangedListener(this)
        contact_search_key.setOnEditorActionListener(this)

        recycler_view.setLayoutManager(LinearLayoutManager(context))
        recycler_view.adapter = mAdapter
        recycler_view.showEmpty()

        contactViewModel.contactFilterList.observe(viewLifecycleOwner, Observer { list ->
            mAdapter.setData(list)
            mAdapter.notifyDataSetChanged()
        })

        group_call_button.setOnClickListener {
            val selected = mAdapter.getSelectedContacts()

            /*if (System.currentTimeMillis() - SystemData.getInstance().hangupTime < 3000) {
                return@setOnClickListener
            }*/
            if (!RoomClientRepository.connected()) {
                toast("网络未连接，暂时无法呼叫")
                return@setOnClickListener
            }

            if (selected.isEmpty()) {
                toast("请选择开会成员")
                return@setOnClickListener
            }

            if (selected.size > AppConstant.MAX_CHOOSE_NUMBER) {
                toast("目前只支持${AppConstant.MAX_CHOOSE_NUMBER + 1}方通话")
                return@setOnClickListener
            }

            val terms: ArrayList<String> = arrayListOf()
            for (i in selected.indices) {
                selected[i].contactNumber?.let {
                    terms.add(it)
                    callLogViewModel.createCallLog(it, "2")
                }
            }

            val call = when {
                terms.size == 1 -> {
                    P2PSingleCall(terms[0])
                }
                terms.size > 1 -> {
                    P2PMultiCall(terms)
                }
                else -> {
                    null
                }
            }

            if (call == null) {
                toast("请选择至少1个开会成员")
                return@setOnClickListener
            }

            call.micOn = switch_mic.isChecked
            call.cameraOn = switch_camera.isChecked

            context?.let { context -> CallActivityA.open(context, call) }
        }
    }

    override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            val keyword = v.text.toString()

            hideKeyboard()

            // 当按了搜索之后关闭软键盘
            /*(Objects.requireNonNull(context)!!.getSystemService(
                    Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(
                    Objects.requireNonNull<View>(Objects.requireNonNull(activity)!!.currentFocus).windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS)*/
            //搜索
            return keyword.isNotEmpty()
        }
        return false
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        contactViewModel.searchWord(if (count > 0) s.toString() else null)
    }

    override fun afterTextChanged(s: Editable?) {}
}
